package com.cgbl.cg.vm.work

import android.app.Application
import androidx.databinding.ObservableField
import api.UserServiceFactory
import api.WorkServiceFactory
import com.blankj.utilcode.util.LogUtils
import com.robot.base.base.vm.GLBaseViewModel
import com.robot.base.common.api.AbstractViewModelSubscriber
import com.robot.base.configs.PrefsManager
import com.robot.base.model.*
import me.goldze.mvvmhabit.binding.command.BindingAction
import me.goldze.mvvmhabit.binding.command.BindingCommand
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent
import me.goldze.mvvmhabit.http.BaseResponse

class WorkDetailsViewModel(application: Application) : GLBaseViewModel(application) {
    var id = ""
    val uc = UiChangeEvent()
    val startSelect = ObservableField(false)

    val head = ObservableField<String>()
    val nickName = ObservableField<String>()
    val workName = ObservableField<String>()
    val viewCount = ObservableField<String>()
    val comentCount = ObservableField<String>()

    val crateDate = ObservableField<String>()
    val workExplain = ObservableField<String>()

    val collectCount = ObservableField<String>()
    val likeCount = ObservableField<String>()
    val list = arrayListOf<CollectDetailBean>()
    val like = ObservableField<Boolean>(false)
    var commentBean = CommentBean()

    val follow = ObservableField(false)
    val followText = ObservableField<String>("+关注")
    var followerAccountId = ""

    val followVisibility = ObservableField(true)

    class UiChangeEvent {

        val showCollectEvent: SingleLiveEvent<String> = SingleLiveEvent()


        val showCommentEvent: SingleLiveEvent<String> = SingleLiveEvent()

        val videoDataEvent: SingleLiveEvent<List<WorksResourceBean>> = SingleLiveEvent()

        val imgDataEvent: SingleLiveEvent<List<WorksResourceBean>> = SingleLiveEvent()

        val refreshCommendDataEvent = SingleLiveEvent<List<CommentBean>>()
        val refreshCommendChildDataEvent = SingleLiveEvent<List<CommentBean>>()

    }

    val showCollectCommand = BindingCommand<Any>(BindingAction {
        uc.showCollectEvent.call()
    })

    val showCommentCommand = BindingCommand<Any>(BindingAction {
        uc.showCommentEvent.call()
    })

    val likeCommand = BindingCommand<Any>(BindingAction {
        likeWork(2)
    })


    val followCommand = BindingCommand<Any>(BindingAction {
        followUsers()
    })

    fun getWorkDetail() {
        WorkServiceFactory.getWorkDetail(id)
            .subscribe(object : AbstractViewModelSubscriber<BaseResponse<WorksBean>>(this) {
                override fun onNext(t: BaseResponse<WorksBean>) {
                    followVisibility.set(t.data.accountId != PrefsManager.getUserLoginInfo().userId)
                    workName.set(t.data.workName)
                    viewCount.set(t.data.viewCount)
                    crateDate.set(t.data.crateDate)
                    workExplain.set(t.data.workExplain)
                    collectCount.set(t.data.collectCount)
                    likeCount.set(t.data.likeCount)
                    head.set(t.data.head)
                    nickName.set(t.data.nickName)
                    comentCount.set(t.data.comentCount)
                    uc.imgDataEvent.postValue(t.data.images)
                    uc.videoDataEvent.postValue(t.data.videos)
                    like.set(t.data.like == 1)
                    followerAccountId = t.data.accountId?:""
                    fetchTeacherInfo(t.data.accountId?:"")
                }
            })
    }

    private fun fetchTeacherInfo(id: String) {
        UserServiceFactory.otherUserInfo(id)
            .subscribe(object : AbstractViewModelSubscriber<BaseResponse<UserInfoBean>>(this) {
                override fun onNext(t: BaseResponse<UserInfoBean>) {

                    follow.set(t.data.follow)
                    followText.set(
                        if (follow.get() == true) {
                            "已关注"
                        } else {
                            "+关注"
                        }
                    )
                }
            })
    }

    fun followUsers() {
        UserServiceFactory.followUsers(
            mapOf(
                "followerAccountId" to followerAccountId
            )
        ).subscribe(object : AbstractViewModelSubscriber<BaseResponse<String>>(this) {
            override fun onNext(t: BaseResponse<String>) {
                LogUtils.e(t)
                follow.set(!(follow.get() ?: false))
                followText.set(
                    if (follow.get() == true) {
                        "已关注"
                    } else {
                        "+关注"
                    }
                )
            }
        })
    }

    fun collectPage(refresh: Boolean = false) {
        WorkServiceFactory.collectPage(
            mapOf(
                "pageNo" to "1",
                "pageSize" to "99",
                "isAccount" to "1"
            )
        ).subscribe(object :
            AbstractViewModelSubscriber<BaseResponse<PageListBean<CollectDetailBean>>>(this) {
            override fun onNext(t: BaseResponse<PageListBean<CollectDetailBean>>) {
                list.clear()
                list.addAll(t.data.list)
                if (refresh) {
                    uc.showCollectEvent.call()
                }
            }
        })
    }

    fun createCollect(collectName: String, conllectInfo: String, status: String) {
        WorkServiceFactory.createCollect(
            mapOf(
                "collectName" to collectName,
                "conllectInfo" to conllectInfo,
                "status" to status
            )
        ).subscribe(object : AbstractViewModelSubscriber<BaseResponse<String>>(this) {
            override fun onNext(t: BaseResponse<String>) {
                collectPage(true)
            }
        })
    }

    fun saveCollectWorks(collectId: String) {
        WorkServiceFactory.saveCollectWorks(
            mapOf(
                "collectId" to collectId,
                "worksInfoId" to id
            )
        ).subscribe(object : AbstractViewModelSubscriber<BaseResponse<String>>(this) {
            override fun onNext(t: BaseResponse<String>) {
                startSelect.set(true)
                collectCount.set("${(collectCount.get()?.toInt() ?: 0) + 1}")
            }
        })
    }

    fun createWorkComment(content: String, parentId: String, accountId: String = "") {
        WorkServiceFactory.createWorkComment(
            mapOf(
                "content" to content,
                "parentId" to parentId,
                "worksId" to id,
                "toAccountId" to accountId
            )
        ).subscribe(object : AbstractViewModelSubscriber<BaseResponse<String>>(this) {
            override fun onNext(t: BaseResponse<String>) {
                if (parentId == "0") {
                    pageCommend(0, "", 0)
                    comentCount.set("${(comentCount.get()?.toInt() ?: 0) + 1}")
                }
            }
        })
    }

    fun pageCommend(allOff: Int, parentId: String, type: Int) {
        WorkServiceFactory.pageComment(
            mapOf(
                "allOff" to allOff,//0：只查1级，1：带2级组装
                "pageNo" to 1,
                "pageSize" to 99,
                "parentId" to parentId,//如果type等于1时，parentId必填，为一级评论的ID。
                "type" to type,//查询层级，一级为0，二级为1
                "worksId" to id
            )
        ).subscribe(object :
            AbstractViewModelSubscriber<BaseResponse<PageListBean<CommentBean>>>(this) {
            override fun onNext(t: BaseResponse<PageListBean<CommentBean>>) {
                if (type == 0) {
                    uc.refreshCommendDataEvent.postValue(t.data.list)
                } else {
                    uc.refreshCommendChildDataEvent.postValue(t.data.list)
                }
            }

        })
    }

    /**
     *  @param type 要增加的数据统计维度,2：点赞，3：分享
     */
    fun likeWork(type: Int) {
        WorkServiceFactory.likeWork(
            mapOf(
                "type" to type,
                "workInfoId" to id
            )
        ).subscribe(object : AbstractViewModelSubscriber<BaseResponse<String>>(this) {
            override fun onNext(t: BaseResponse<String>) {
                if (like.get() == true) {
                    likeCount.set("${(likeCount.get()?.toInt() ?: 0) - 1}")
                } else {
                    likeCount.set("${(likeCount.get()?.toInt() ?: 0) + 1}")
                }
                like.set(!(like.get() ?: false))
            }
        })
    }
}